<?php

namespace IMT\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use IMT\UserBundle\Entity\Contact;
use IMT\UserBundle\Form\ContactType;

/**
 * Contact controller.
 *
 */
class ContactController extends Controller
{
    /**
     * Lists all Contact entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->get('security.context')->getToken()->getUser();
		$entities = array();
        
        $accounts = $em->getRepository('IMTAccountBundle:Account')->findAllByUser($user);
        
        foreach($accounts as $account){
        	foreach($account->getContacts() as $contact){
        		$entities[$contact->getId()] = $contact;
        	}
        }

        return $this->render('IMTUserBundle:Contact:index.html.twig', array(
            'entities' => $this->getContactList($entities, $user)
        ));
    }

    /**
     * Finds and displays a Contact entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('IMTUserBundle:Contact')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Contact entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('IMTUserBundle:Contact:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),

        ));
    }

    /**
     * Displays a form to create a new Contact entity.
     *
     */
    public function newAction()
    {
        $entity = new Contact();
        $user = $this->get('security.context')->getToken()->getUser();
        
        $form   = $this->createForm(new ContactType(), $entity, array(
        	'user' => $user
        ));
        return $this->render('IMTUserBundle:Contact:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }

    /**
     * Creates a new Contact entity.
     *
     */
    public function createAction()
    {
        $entity  = new Contact();
        $user = $this->get('security.context')->getToken()->getUser();
                
        $request = $this->getRequest();
        $form    = $this->createForm(new ContactType(), $entity, array(
        	'user' => $user
        ));
        
        $form->bindRequest($request);

        if ($form->isValid()) {
        	
        	if(sizeof($entity->getAccounts()) == 0){
        		$this->get('session')->setFlash('error', 'Vous devez indiquer au moins 1 compte');
        		
        		return $this->render('IMTUserBundle:Contact:new.html.twig', array(
        				'entity' => $entity,
        				'form'   => $form->createView()
        		));
        	}
        	
        	$em = $this->getDoctrine()->getEntityManager();
        	
        	$contacts = $em->getRepository('IMTUserBundle:Contact')->findBy(array(
        		'email' => $entity->getEmail()
        	));
        	        	
        	if(is_array($contacts) && sizeof($contacts) > 0){
        		foreach($contacts as $contact){
        			if($contact->getUser()){
	        			$contact->addContactUser($entity);
	        			
	        			$em->persist($contact);
	        			$em->flush();
        			}
        		}
        	}
        	
        	foreach($entity->getAccounts() as $account){
        		$account->addContact($entity);
        		
        		$em->persist($account);
        		$em->flush();
        	}
                        
            $this->get('session')->setFlash('success', 'Un contact a été créé');

            return $this->redirect($this->generateUrl('imt_user_contact'));
            
        }

        return $this->render('IMTUserBundle:Contact:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }

    /**
     * Displays a form to edit an existing Contact entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('IMTUserBundle:Contact')->find($id);
        $user = $this->get('security.context')->getToken()->getUser();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Contact entity.');
        }

        $editForm = $this->createForm(new ContactType(), $entity, array(
        	'user' => $user
        ));
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('IMTUserBundle:Contact:edit.html.twig', array(
            'entity'      => $entity,
            'form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing Contact entity.
     *
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('IMTUserBundle:Contact')->find($id);
        $user = $this->get('security.context')->getToken()->getUser();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Contact entity.');
        }

        $editForm   = $this->createForm(new ContactType(), $entity, array(
        	'user' => $user
        ));
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            if(sizeof($entity->getAccounts()) == 0){
        		$this->get('session')->setFlash('alert', 'Vous devez indiquer au moins 1 compte');
        		
        		return $this->render('IMTUserBundle:Contact:edit.html.twig', array(
		            'entity'      => $entity,
		            'form'   => $editForm->createView(),
		            'delete_form' => $deleteForm->createView(),
		        ));
        	}
        	
        	$em = $this->getDoctrine()->getEntityManager();
        	 
        	$contacts = $em->getRepository('IMTUserBundle:Contact')->findBy(array(
        			'email' => $entity->getEmail()
        	));
        	
        	$entity->setContactLink(null);
        	        	 
        	if(is_array($contacts) && sizeof($contacts) > 0){
        		foreach($contacts as $contact){
        			if($contact->getUser()){
        				$contact->addContactUser($entity);
        	
        				$em->persist($contact);
        				$em->flush();
        			}
        		}
        	}
        	 
        	foreach($entity->getAccounts() as $account){
        		$account->addContact($entity);
        	
        		$em->persist($account);
        		$em->flush();
        	}
        	
        	foreach($entity->getAccounts() as $account){
        		$account->addContact($entity);
        		
        		$em->persist($account);
        		$em->flush();
        	}
                        
            $this->get('session')->setFlash('success', 'Un contact a été modifié');

            return $this->redirect($this->generateUrl('imt_user_contact'));
        }

        return $this->render('IMTUserBundle:Contact:edit.html.twig', array(
            'entity'      => $entity,
            'form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    
    public function profilEditAction($id)
    {
    	$em = $this->getDoctrine()->getEntityManager();
    
    	$entity = $em->getRepository('IMTUserBundle:Contact')->find($id);
    
    	if (!$entity) {
    		throw $this->createNotFoundException('Unable to find Contact entity.');
    	}
    
    	$editForm = $this->createForm(new ContactType(), $entity);
    	$deleteForm = $this->createDeleteForm($id);
    
    	return $this->render('IMTUserBundle:Contact:profil_edit.html.twig', array(
    			'entity'      => $entity,
    			'form'   => $editForm->createView(),
    			'delete_form' => $deleteForm->createView(),
    	));
    }
    
    /**
     * Edits an existing Contact entity.
     *
     */
    public function profilUpdateAction($id)
    {
    	$em = $this->getDoctrine()->getEntityManager();
    
    	$entity = $em->getRepository('IMTUserBundle:Contact')->find($id);
    
    	if (!$entity) {
    		throw $this->createNotFoundException('Unable to find Contact entity.');
    	}
    
    	$editForm   = $this->createForm(new ContactType(), $entity);
    	$deleteForm = $this->createDeleteForm($id);
    
    	$request = $this->getRequest();
    
    	$editForm->bindRequest($request);
    
    	if ($editForm->isValid()) {
    		$em->persist($entity);
    		$em->flush();
    
    		return $this->redirect($this->generateUrl('fos_user_profile_show'));
    	}
    
    	return $this->render('IMTUserBundle:Contact:profil_edit.html.twig', array(
    			'entity'      => $entity,
    			'form'   => $editForm->createView(),
    			'delete_form' => $deleteForm->createView(),
    	));
    }

    /**
     * Deletes a Contact entity.
     *
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('IMTUserBundle:Contact')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Contact entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('imt_user_contact'));
    }
    
    public function deleteMultiAction($listIds)
    {
    	if($listIds == ''){
    		$this->get('session')->setFlash('warning', 'Aucune réservation n\'a été selectionnée');
    	} else {
    		$arrayIds = explode(',', $listIds);
    		$countDeleted = 0;
    		$totalDelete = 0;
    		 
    		$em = $this->getDoctrine()->getManager();
    		 
    		foreach($arrayIds as $id){
    			$id = intval($id);
    
    			if($id != 0){
    				$totalDelete++;
    				$entity = $em->getRepository('IMTUserBundle:Contact')->find($id);
    					
    				if ($entity) {    						
    					$em->remove($entity);
    					$em->flush();
    					$countDeleted++;
    				}
    			}
    		}
    		 
    		if($countDeleted == $totalDelete)
    			$this->get('session')->setFlash('success', ($totalDelete == 1) ? 'La réservation a été supprimée' : 'Les réservations ont été supprimées');
    		else
    			$this->get('session')->setFlash('error', ($totalDelete == 1) ? 'La réservation n\'a pas pu être supprimée' : 'Toutes les réservations n\'ont pas pu être supprimées');
    	}
    
    	return $this->redirect($this->generateUrl('brossette_reservation_reservation'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    
    public static function getContactList($contacts, $user)
    {
    	$indexs = array(
    			'#' => array('title' =>'#', 'values' => array()),
    			'a' => array('title' =>'A', 'values' => array()),
    			'b' => array('title' =>'B', 'values' => array()),
    			'c' => array('title' =>'C', 'values' => array()),
    			'd' => array('title' =>'D', 'values' => array()),
    			'e' => array('title' =>'E', 'values' => array()),
    			'f' => array('title' =>'F', 'values' => array()),
    			'g' => array('title' =>'G', 'values' => array()),
    			'h' => array('title' =>'H', 'values' => array()),
    			'i' => array('title' =>'I', 'values' => array()),
    			'j' => array('title' =>'J', 'values' => array()),
    			'k' => array('title' =>'K', 'values' => array()),
    			'l' => array('title' =>'L', 'values' => array()),
    			'm' => array('title' =>'M', 'values' => array()),
    			'n' => array('title' =>'N', 'values' => array()),
    			'o' => array('title' =>'O', 'values' => array()),
    			'p' => array('title' =>'P', 'values' => array()),
    			'q' => array('title' =>'Q', 'values' => array()),
    			'r' => array('title' =>'R', 'values' => array()),
    			's' => array('title' =>'S', 'values' => array()),
    			't' => array('title' =>'T', 'values' => array()),
    			'u' => array('title' =>'U', 'values' => array()),
    			'v' => array('title' =>'V', 'values' => array()),
    			'w' => array('title' =>'W', 'values' => array()),
    			'x' => array('title' =>'X', 'values' => array()),
    			'y' => array('title' =>'Y', 'values' => array()),
    			'z' => array('title' =>'Z', 'values' => array()),
    	);
    	 
    	foreach($contacts as $contact){
    		if(!$contact->getUser() || ($contact->getUser() && $user->getId() != $contact->getUser()->getId())){
	    		$index = strtolower(substr($contact, 0, 1));
	    		$indexs[(isset($indexs[$index])) ? $index : '#']['values'][] = $contact;
    		}
    	}
    	 
    	foreach($indexs as $name => $index){
    		if(sizeof($index['values']) == 0) unset($indexs[$name]);
    	}
    	 
    	return $indexs;
    }
}
